package com.pomr.util.common;

import org.apache.http.HttpEntity;
import org.apache.http.HttpStatus;
import org.apache.http.NameValuePair;
import org.apache.http.StatusLine;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.alibaba.fastjson.JSONObject;
import com.pomr.controller.common.ExceptionLogController;
import com.pomr.util.communication.CXParam;

import java.io.IOException;
import java.security.MessageDigest;
import java.util.*;
import java.util.Map.Entry;

/**
 * @作者：Administrator
 * @时间：18:27 2018/5/3 0003
 * @用途：SIM信息查询接口工具类
 **/
public class SIMConnection {
	private static Logger log = LoggerFactory.getLogger(SIMConnection.class);
	
	private static final char[] HEX_CHAR = {'0', '1', '2', '3', '4', '5', 
            '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'};
	
	public static String mainMessage(CXParam c, String url) throws Exception{
		return searchMessage(getParam(c),url);
	}
	
	/**
	 * post方式调用接口
	 * @param jb 完整参数JSON
	 * @param url 接口地址
	 * @return
	 * @throws Exception
	 */
    public static String searchMessage(JSONObject jb, String url) throws Exception{
        CloseableHttpClient httpclient = HttpClients.createDefault();
        HttpPost httpPost = new HttpPost(url);// 创建httpPost
        httpPost.setHeader("Accept", "application/json");
        httpPost.setHeader("Content-Type", "application/json");
        String charSet = "UTF-8";
        
        StringEntity entity = new StringEntity(jb.toJSONString(), charSet);
        httpPost.setEntity(entity);
        CloseableHttpResponse response = null;

        try {
            response = httpclient.execute(httpPost);
            StatusLine status = response.getStatusLine();
            int state = status.getStatusCode();
            if (state == HttpStatus.SC_OK) {
                HttpEntity responseEntity = response.getEntity();
                String jsonString = EntityUtils.toString(responseEntity);
                log.info(" 入参："+url+"?"+jb.toJSONString()+" 返回值："+jsonString);
                return jsonString;
            }else{
//                 logger.error("请求返回:"+state+"("+url+")");
            }
        }finally {
            if (response != null) {
                try {
                    response.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            try {
                httpclient.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return null;
    }

    /*
     *@作者：Administrator
     *@时间：18:22 2018/5/3 0003
     *@用途：获取签名并返回完整参数
     *
     */
    public static JSONObject getParam(CXParam c) throws Exception{
    	TreeMap map = c.toMap();
        map.put("secret","dVHPErC7K1LO4dOOkFaK2TYl5Hcs8myD");
        String signstr = createSign(map,"5Ktul9tEP2");
        JSONObject jb = c.toJson();
        jb.put("secret","dVHPErC7K1LO4dOOkFaK2TYl5Hcs8myD");
        jb.put("sign", signstr);
        return jb;
    }


    /**
     * 日期格式字符串转换成unix时间戳
     * @return
     */
    public static String Date2TimeStamp() {
        try {
            return String.valueOf((new Date()).getTime() / 1000);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "";
    }
    
    
    
    /**
     * 字节数组转为16进制字符串
     * @param bytes
     * @return
     */
    public static String bytesToHexFun2(byte[] bytes) {
        char[] buf = new char[bytes.length * 2];
        int index = 0;
        for(byte b : bytes) { // 利用位运算进行转换，可以看作方法一的变种
            buf[index++] = HEX_CHAR[b >>> 4 & 0xf];
            buf[index++] = HEX_CHAR[b & 0xf];
        }

        return new String(buf);
    }
    
    /**
     * md5加密
     * @param origin
     * @param charsetname
     * @return
     */
  	public static String MD5Encode(String origin, String charsetname) {
  			String resultString = null;
  			try {
  				resultString = new String(origin);
  				MessageDigest md = MessageDigest.getInstance("MD5");
  				if (charsetname == null || "".equals(charsetname))
  					resultString = SIMConnection.bytesToHexFun2(md.digest(resultString
  							.getBytes()));
  				else
  					resultString = SIMConnection.bytesToHexFun2(md.digest(resultString
  							.getBytes(charsetname)));
  			} catch (Exception exception) {
  			}
  			return resultString;
  		}


  	 
  	public static String getData(Object value){
  			if(null == value)
  				return "";
  			else 
  				return value.toString();
  		}
  	
  	/**
  	 * 获取加密sign
  	 * @param packageParams
  	 * @param appSercet
  	 * @return
  	 * @throws Exception
  	 */
  	public static String createSign(Map<String, String> packageParams,String appSercet) throws Exception{
  		StringBuffer sb = new StringBuffer();
  		Set es = packageParams.entrySet();
  		Iterator it = es.iterator();
  		while (it.hasNext()) {
  			Map.Entry entry = (Map.Entry) it.next();
  			String k = getData(entry.getKey());
  			String v = getData(entry.getValue());
  			if (null != v && !"".equals(v)) {
  				sb.append(k + "=" + v + "&");
  			}
  		}
  		sb.append("appSecret=" + appSercet);
  		System.out.println("URL 键值对："+sb.toString());
  		String sign = MD5Encode(sb.toString(), "UTF-8").toUpperCase();
  		return sign;
  	}//加密方式

    
    /*
     *@作者：Administrator
     *@时间：17:41 2018/5/3 0003
     *@用途：测试信息调用main
     *
     */
    public static void main(String args[]) throws Exception{
        
    }
}
